import java.util.*;

/**
 * @author LKQ
 * @date 2022/3/18 9:18
 * @description 字典树，单词长度排序后，短单词先加入
 */
public class Solution {
    Trie trie = new Trie();
    public static void main(String[] args) {
        Solution solution = new Solution();
        String[] words = {"cat","cats","catsdogcats","dog","dogcatsdog"};
        solution.findAllConcatenatedWordsInADict(words);
    }
    public List<String> findAllConcatenatedWordsInADict(String[] words) {
        List<String> ans = new ArrayList<>();
        // 单词长度升序排列
        Arrays.sort(words, (a,b)-> a.length() - b.length());
        for (int i = 0; i < words.length; i++) {
            String word = words[i];
            if (word.length() == 0) {
                continue;
            }
            boolean[] visited = new boolean[word.length()];
            if (dfs(word, 0, visited)) {
                ans.add(word);
            }else {
                insert(word);
            }
        }
        return ans;
    }
    public boolean dfs(String word, int start, boolean[] visited) {
        if (word.length() == start) {
            // 该单词所有下标都匹配完成后
            return true;
        }
        if (visited[start]) {
            return false;
        }
        visited[start] = true;
        Trie node = trie;
        for (int i = start; i < word.length() ; i++) {
            char ch = word.charAt(i);
            int index = ch - 'a';
            node = node.children[index];
            if (node == null) {
                return false;
            }
            if (node.isEnd) {
                // 如果一个字符对应的结点是单词的结尾，那么找到了一个更短的单词，然后从该字符下一个字符开始搜索下一个更短的单词
                if (dfs(word, i+1, visited)) {
                    return true;
                }
            }
        }
        return false;
    }
    public void insert(String word) {
        Trie node = trie;
        for (int i = 0; i < word.length(); i++) {
            char ch = word.charAt(i);
            int index = ch - 'a';
            if (node.children[index] == null) {
                node.children[index] = new Trie();
            }
            node = node.children[index];
        }
        node.isEnd = true;
    }


}
class Trie{
    Trie[] children;
    boolean isEnd;

    public Trie() {
        children = new Trie[26];
        isEnd = false;
    }
}